package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 目标:
 *
 * @author YUE
 * @date 2024/6/23 10:52
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 0/1 * * * ?")  // 每分钟查询一次
    public void processTimeoutOrder() {
        log.info("处理未付款的订单{}", LocalDateTime.now());

        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> orders = orderMapper.getByStatusAndTimeLT(Orders.PENDING_PAYMENT, localDateTime);
        // 修改订单状态
        for (Orders order : orders) {
            order.setStatus(Orders.CANCELLED);
            order.setCancelReason("支付超时,自动取消");
            order.setCancelTime(LocalDateTime.now());
            orderMapper.update(order);
        }
    }
  //  Delivery
    @Scheduled(cron = "0 0 1 * * ?")  // 每天一点拆查询
    public void processDeliveryOrder(){
        log.info("处理派送中订单{}",LocalDateTime.now());

        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> byStatusAndTimeLT = orderMapper.getByStatusAndTimeLT(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        for (Orders orders : byStatusAndTimeLT) {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());  // 送达时间
            orderMapper.update(orders);
        }

    }

}
